package doru;


import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.swing.JFileChooser;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.border.EtchedBorder;
import javax.swing.table.TableCellRenderer;
import net.miginfocom.swing.MigLayout;
import java.awt.TextArea;



public class EvalUrl {

	private JFrame frmDoruDomainResearch;
	private TextArea domainLookupField;
	private static JTable domainTable;


	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					EvalUrl window = new EvalUrl();
					window.frmDoruDomainResearch.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public EvalUrl() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame. 
	 */
	private void initialize() {

		
		frmDoruDomainResearch = new JFrame();
		frmDoruDomainResearch.setTitle("Doru Domain Research Utility");
		frmDoruDomainResearch.setBounds(100, 100, 716, 675);
		frmDoruDomainResearch.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frmDoruDomainResearch.getContentPane().setLayout(new MigLayout("", "[714px]", "[641px]"));

		JPanel panel = new JPanel();
		panel.setLayout(null);
		frmDoruDomainResearch.getContentPane().add(panel, "cell 0 0,grow");

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(6, 0, 696, 534);
		scrollPane.setViewportBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		panel.add(scrollPane);

		//create table using custom JTable model
		domainTable = new JTable(new DomainTableModel());
		scrollPane.setViewportView(domainTable);
		TableCellRenderer renderer = new ColorCells(domainTable);
        try
        {
            domainTable.setDefaultRenderer( Class.forName
               ( "java.lang.String" ), renderer );
        }
        catch( ClassNotFoundException ex )
        {
            System.exit( 0 );
        }
        LoadConfig loadConfig = new LoadConfig();
    	
		
        // creates field for user to enter domain. needs to have code for submit
		// on enter created.
        domainLookupField = new TextArea();
        
		domainLookupField.setBounds(6, 546, 511, 78);
		panel.add(domainLookupField);
		domainLookupField.setColumns(10);
		
		/**	domainLookupField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				// submit whatever is in the text box to method for entry to table
				String field = domainLookupField.getText();
				if (!field.contentEquals("")) {
					writeDomainCheckToTable(domainLookupField.getText());
				}
			}
		});	*/	

		/**
		 * if no text exists in domainlookupfield opens file dialog for user to point to domain file
		 * if something is in the text box submits it to method for adding to table.
		 */
		JButton loadFromFileButton = new JButton("Load");
		loadFromFileButton.setBounds(523, 546, 98, 25);
		panel.add(loadFromFileButton);
		loadFromFileButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				// Prompt for file selection from user
				JFileChooser myChooser = new JFileChooser();
				System.out.println(domainLookupField.getText());
				String field = domainLookupField.getText();
				if (field.contentEquals("") && myChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
					File myFile = myChooser.getSelectedFile();

					// read file
					try {
						FileInputStream fstream = new FileInputStream(myFile);
						DataInputStream in = new DataInputStream(fstream);
						BufferedReader br = new BufferedReader(
								new InputStreamReader(in));
						String strLine; 

						while ((strLine = br.readLine()) != null) {
							writeDomainCheckToTable(strLine);
						}

					} catch (Exception e) {
						System.err.println("Error: " + e.getMessage());
					}

				}else{
					//EatTheText(domainLookupField.getText());
					writeDomainCheckToTable(domainLookupField.getText());
				}
				domainLookupField.setText("");
			}
		});
		
		/**
		 * creates session files from rows selected in table by sending selected rows to session method.
		 */
		JButton createSessionsbutton = new JButton("Create Session Files");
		createSessionsbutton.setBounds(523, 599, 179, 25);
		panel.add(createSessionsbutton);
		createSessionsbutton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				int[] selected = domainTable.getSelectedRows(); //get selected rows and put in int array
				for (int i = 0; i < selected.length; i++) { //for as many items as are in the array
					String url = (String) domainTable.getValueAt(selected[i], 0); //get value of just first column of selected rows
					writeSessionFile(url); //send value to method to write to disk
				}
			}
		});
	}

	/**
	 * this removes the standard obs used to stop windows from creating links.
	 * because this has no problems when run on clean domains I run it whenever
	 * a domain value is moved around. This prevents strange problems when
	 * making web requests.
	 */
	private static String makeValidUrl(String url) {
		if (url.contains("[") == true) {
			String workedUrl = url.replace("[.]", ".");
			workedUrl = workedUrl.replace("[d]", ".");
			workedUrl = workedUrl.replace("[dot]", ".");
			return workedUrl;
		}
		return url;
	}
	
	/**
	 * didn't really need to make this its own method but here we are. all TLDs
	 * start (and only contain) letters. if the char to the right of the last
	 * period is a number we have an IP otherwise it has to be a domain.
	 */
	private static boolean isThisAnIP(String url) {
		int index = url.lastIndexOf('.');
		index += 1;
		return Character.isDigit(url.charAt(index));
	}

	
	/**
	 * This is where speed issues can come from. Takes in string for domain/ip and makes it valid(removes [d] for instance.
	 * sends to instance of checkurl and writes the result to domain table.
	 * if speed is slow might be worth creating seperate checkurl instances for every request( or just norton).
	 */
	private static void writeDomainCheckToTable(String domainLookupFieldText){
		String domain = makeValidUrl(domainLookupFieldText);
		
		
		CheckUrl checkurl = new CheckUrl(domain);
		int rowPosition = domainTable.getRowCount() -1; //you start counting at zero, if not overruns table.
		
		//get string from checkurl.
		String whoops = (String) domainTable.getValueAt(0, 1);
		domainTable.setValueAt(domain, rowPosition, 0);
		
		if(!whoops.contentEquals("Site Error")){
		domainTable.setValueAt(checkurl.googleResult(), rowPosition, 1);
		domainTable.setValueAt(checkurl.nortonResult(), rowPosition, 2);
		domainTable.setValueAt(checkurl.mcafeeResult(), rowPosition, 3);
		domainTable.setValueAt(checkurl.mywotResult(), rowPosition, 4);
		}
		domainTable.setValueAt(checkBlockList(domain), rowPosition, 5);

			
		 
	}
	
	private static String checkBlockList(String domain){
		
		String blockList = LoadConfig.blocked;
		domain = domain.replaceAll("\\.(?!.*\\.)", "[d]");
		System.out.println(domain);
		if(blockList.contains(domain)){
			return "Already-Blocked";
		}
		return "UnBlocked";
	}
	

	
	/**
	 *this takes raw domain name and creates session file. also calls the is
	 * this ip method to decide which session file defaults to use. 
	 */

	private static void writeSessionFile(String urlLine) {
		//get default session file structure from local file or defaults
		LoadConfig loadConfig = new LoadConfig();
		String baseUrl = loadConfig.UrlBase();
		String baseIP = loadConfig.IPBase();
		
		
		String basetext;
		urlLine = makeValidUrl(urlLine);
		String fileName = urlLine.concat(".session"); // creates correct filename

		// IP address get a different session layout, this checks for that.
		if (isThisAnIP(urlLine) == true) {
			basetext = baseIP;
		} else {
			basetext = baseUrl;
		}
		// adds url to basetext by replacing FILLMEIN
		String replacedUrl = basetext.replace("FILLMEIN", urlLine);

		FileOutputStream sessionFile;
		
		try {
			sessionFile = new FileOutputStream(fileName);
			Writer sessionOut = new OutputStreamWriter(sessionFile, "UTF8"); //UTF8 required for cross-platform usage.
			
			sessionOut.write("[SessionManager v2]\r\n");
			sessionOut.write("name=FILLMEIN\r\n");
			sessionOut.write("timestamp=1294320493620\r\n");
			sessionOut.write("autosave=false	count=1/10	group=Research	screensize=1920x1200\r\n");
			sessionOut.write(replacedUrl);
			
			sessionOut.close();
		} catch (FileNotFoundException e) {
			// very bad times if this hits, check security settings
			e.printStackTrace();
		} catch (IOException e) {
			// very bad times if this hits, check security settings
			e.printStackTrace();
		}

	}
}
